package com.wl.controller;

import com.aliyuncs.utils.StringUtils;
import com.wl.pojo.Users;
import com.wl.pojo.model.UserToken;
import com.wl.response.CommonReturnType;
import com.wl.service.UsersService;
import com.wl.service.impl.UsersServiceImpl;
import com.wl.util.MyUtil;
import com.wl.util.TokenUtils;
import lombok.SneakyThrows;
import org.jose4j.lang.JoseException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-06 20:48
 */
@WebServlet("/user.action")
public class UserServlet extends BaseServlet {

    private UsersService usersService = new UsersServiceImpl();

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        if (com.mysql.cj.util.StringUtils.isNullOrEmpty(op)) {
            show404Common(request, response);
            return;
        }
        if ("login".equals(op)) {
            loginOp(request, response);
        } else if ("register".equals(op)) {
            registerOp(request, response);
        } else if ("update".equals(op)) {
            updateOp(request, response);
        } else if ("loginOut".equals(op)) {
            loginOutOp(request, response);
        } else if ("checkTelIsOk".equals(op)) {
            checkTelIsOkOp(request, response);
        } else if ("checkIsLogin".equals(op)) {
            checkIsLoginOp(request, response);
        } else if ("getUserInfo".equals(op)) {
            getUserInfoOp(request, response);
        } else if ("checkUserPwd".equals(op)) {
            checkUserPwdOp(request, response);
        } else if ("checkValCode".equals(op)) {
            checkValCodeOp(request, response);
        } else if ("adminLogin".equals(op)) {
            adminLoginOp(request, response);
        } else if ("adminLoginOut".equals(op)) {
            adminLoginOutOp(request, response);
        } else if ("getAdmin".equals(op)) {
            getAdminOp(request, response);
        } else if ("getAllUser".equals(op)) {
            getAllUserOp(request, response);
        } else if ("deleteArticle".equals(op)) {
            deleteArticleOp(request, response);
        } else if ("updateUser".equals(op)) {
            updateUserOp(request, response);
        } else if ("addFace".equals(op)) {
            addFaceOp(request, response);
        } else if ("loginFace".equals(op)) {
            loginFaceOp(request, response);
        } else if ("checkUserIsOwnerFace".equals(op)) {
            checkUserIsOwnerFaceOp(request, response);
        } else {
            show404Common(request, response);
        }
    }

    /**
     * 检查用户是否已经注册人脸
     *
     * @param request
     * @param response
     */
    private void checkUserIsOwnerFaceOp(HttpServletRequest request, HttpServletResponse response) {
        boolean b = usersService.checkUserIsOwnerFace(request);
        if (b) {
            MyUtil.responseData(response, CommonReturnType.success(""));
        } else {
            MyUtil.responseData(response, CommonReturnType.fail(""));
        }
    }

    /**
     * 人脸登录操作
     *
     * @param request
     * @param response
     */
    private void loginFaceOp(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = usersService.loginFaceOp(request);
        if (map == null) {
            MyUtil.responseData(response, CommonReturnType.fail("采集人脸失败，请调整角度再试"));
        } else {
            MyUtil.responseData(response, CommonReturnType.success(map));
        }
    }

    /**
     * 添加人脸操作
     *
     * @param request
     * @param response
     */
    private void addFaceOp(HttpServletRequest request, HttpServletResponse response) {
        int i = usersService.addFaceOp(request);
        if (i == 3) {
            MyUtil.responseData(response, CommonReturnType.fail("您已经在另外的账号上采集过了"));
            return;
        }
        if (i == -1) {
            MyUtil.responseData(response, CommonReturnType.fail("人像采集失败"));
        } else if (i == 1) {
            MyUtil.responseData(response, CommonReturnType.success("录入成功"));
        } else {
            MyUtil.responseData(response, CommonReturnType.success("更新成功"));
        }
    }

    /**
     * 管理员删除用户
     *
     * @param request
     * @param response
     */

    private void deleteArticleOp(HttpServletRequest request, HttpServletResponse response) {
        Users users = MyUtil.getTFromRequest(Users.class, request);
        boolean b = usersService.deleteUsersById(users);
        if (b) {
            MyUtil.responseData(response, CommonReturnType.success(true));
        } else {
            MyUtil.responseData(response, CommonReturnType.fail("删除用户失败"));
        }
    }


    /**
     * 根据条件获取用户或者管理员或者全部
     *
     * @param request
     * @param response
     */
    private void getAllUserOp(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = usersService.getAllUserBySome(request);
        if (map == null || map.size() <= 0) {
            MyUtil.responseData(response, CommonReturnType.fail(""));
        } else {
            MyUtil.responseData(response, CommonReturnType.success(map));
        }
    }

    /**
     * 从Session中获取登录的管理员
     *
     * @param request
     * @param response
     */

    private void getAdminOp(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = usersService.getAdmin(request);
        if (map == null || map.size() <= 0) {
            MyUtil.responseData(response, CommonReturnType.fail("请先登录"));
        } else {
            MyUtil.responseData(response, CommonReturnType.success(map));
        }
    }


    /**
     * 管理员退出
     *
     * @param request
     * @param response
     */
    private void adminLoginOutOp(HttpServletRequest request, HttpServletResponse response) {
        boolean result = usersService.adminLoginOut(request);
        if (result == false) {
            MyUtil.responseData(response, CommonReturnType.fail("您还没有登录"));
        } else {
            MyUtil.responseData(response, CommonReturnType.success(""));
        }
    }

    /**
     * 管理员登录
     *
     * @param request
     * @param response
     */
    private void adminLoginOp(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = usersService.adminLogin(request);
        if (map == null || map.size() <= 0) {
            MyUtil.responseData(response, CommonReturnType.fail("您不是管理员，无法登录"));
        } else {
            MyUtil.responseData(response, CommonReturnType.success(map));
        }
    }

    /**
     * 验证图片验证码
     *
     * @param request
     * @param response
     */
    private void checkValCodeOp(HttpServletRequest request, HttpServletResponse response) {
        String valCode = request.getParameter("valCode");
        if (StringUtils.isEmpty(valCode)) {
            MyUtil.responseData(response, CommonReturnType.fail(""));
        }
        HttpSession session = request.getSession();
        String validateCode = (String) session.getAttribute("validateCode");
        if (valCode.equals(validateCode)) {
            MyUtil.responseData(response, CommonReturnType.success(""));
        } else {
            MyUtil.responseData(response, CommonReturnType.fail(""));
        }
    }

    /**
     * 检查用户修改密码的时候旧密码是否正确
     *
     * @param request
     * @param response
     */
    private void checkUserPwdOp(HttpServletRequest request, HttpServletResponse response) {
        boolean b1 = checkToken(request, response);
        if (!b1) {
            MyUtil.responseData(response, CommonReturnType.fail("请登录后再执行此操作"));
            return;
        }
        boolean b = usersService.checkUserPwdOp(request);
        MyUtil.responseData(response, CommonReturnType.success(b));
    }

    /**
     * 根据用户Id获取用户的基本信息
     *
     * @param request
     * @param response
     */
    private void getUserInfoOp(HttpServletRequest request, HttpServletResponse response) {
        Users user = usersService.getUserById(request.getParameter("userId"));
        user.setUserPassword("");
        MyUtil.responseData(response, CommonReturnType.success(user));
    }

    /**
     * 检查用户是否登录
     *
     * @param request
     * @param response
     */
    private void checkIsLoginOp(HttpServletRequest request, HttpServletResponse response) {
        String token = TokenUtils.parseTokenToken(request);
        if (StringUtils.isEmpty(token)) {
            MyUtil.responseData(response, CommonReturnType.fail("用户没有登录"));
            return;
        }
        UserToken userToken = TokenUtils.parseTokenToUserToken(token);
        Users user = usersService.getUserById(userToken.getUserId());
        user.setUserPassword("");
        MyUtil.responseData(response, CommonReturnType.success(user));
    }

    /**
     * 注册的时候检查手机号是否有效
     *
     * @param request
     * @param response
     */
    private void checkTelIsOkOp(HttpServletRequest request, HttpServletResponse response) {
        String userTelephoneNumber = request.getParameter("userTelephoneNumber");
        boolean telIsOkOp = usersService.checkTelIsOkOp(userTelephoneNumber);
        MyUtil.responseData(response, CommonReturnType.success(telIsOkOp));
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     */
    @SneakyThrows
    private void loginOutOp(HttpServletRequest request, HttpServletResponse response) {
        boolean b = checkToken(request, response);
        if (!b) {
            MyUtil.responseData(response, CommonReturnType.fail("请登录后再执行此操作"));
            return;
        }
        usersService.loginOut(request);
        MyUtil.responseData(response, CommonReturnType.success(null));
    }

    /**
     * 更新用户信息
     *
     * @param request
     * @param response
     */
    @SneakyThrows
    private void updateOp(HttpServletRequest request, HttpServletResponse response) {
        boolean b = checkToken(request, response);
        if (!b) {
            MyUtil.responseData(response, CommonReturnType.fail("请登录后再执行此操作"));
            return;
        }
        Users users = MyUtil.getTFromRequest(Users.class, request);
        UserToken user = TokenUtils.getUser(request);
        users.setUserId(user.getUserId());
        boolean update = usersService.update(users);
        if (update) {
            MyUtil.responseData(response, CommonReturnType.success("更新信息成功"));
        } else {
            MyUtil.responseData(response, CommonReturnType.fail("更新信息失败"));
        }
    }

    /**
     * 管理员更新用户信息
     *
     * @param request
     * @param response
     */
    @SneakyThrows
    private void updateUserOp(HttpServletRequest request, HttpServletResponse response) {
        Users users = MyUtil.getTFromRequest(Users.class, request);
        users.setUserId(users.getUserId());
        boolean update = usersService.update(users);
        if (update) {
            MyUtil.responseData(response, CommonReturnType.success("更新信息成功"));
        } else {
            MyUtil.responseData(response, CommonReturnType.fail("更新信息失败"));
        }
    }

    /**
     * 用户注册操作
     *
     * @param request
     * @param response
     */
    @SneakyThrows
    private void registerOp(HttpServletRequest request, HttpServletResponse response) {
        Users users = MyUtil.getTFromRequest(Users.class, request);
        Map<String, Object> map = usersService.register(users);
        if (map == null) {
            MyUtil.responseData(response, CommonReturnType.fail("注册失败"));
        } else {
            MyUtil.responseData(response, CommonReturnType.success(map));
        }
    }

    /**
     * 用户登录操作
     *
     * @param request
     * @param response
     */
    private void loginOp(HttpServletRequest request, HttpServletResponse response) throws IOException, JoseException {
        String userTelPhoneOrEmail = request.getParameter("userTelPhoneOrEmail");
        String password = request.getParameter("userPassword");
        Map<String, Object> map = usersService.login(userTelPhoneOrEmail, password);
        MyUtil.responseData(response, CommonReturnType.success(map));
    }
}
